package teshop.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import teshop.dao.CategoryDAO;
import teshop.domain.Category;

/**
 * Created: 25.02.2009
 * @author Hryhory Lira
 *
 */
@Repository
public class CategoryDAOWithJPA implements CategoryDAO {
	
	@PersistenceContext
	protected EntityManager entityManager;

	/**
	 * @return the entityManager
	 */
	public EntityManager getEntityManager() {
		return entityManager;
	}

	/**
	 * @param entityManager the entityManager to set
	 */
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public void delete(Long categoryId) {
		entityManager.createQuery("DELETE FROM Category c WHERE c.categoryId=:id").setParameter("id", categoryId).executeUpdate();		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Category> getSubCategories(Long categoryId) {
		Query query = entityManager.createQuery("SELECT c FROM Category c WHERE c.parentCategory.categoryId=:id");
		query.setParameter("id", categoryId);
		
		return query.getResultList();
	}

	@Override
	public Category loadById(Long categoryId) {
		return entityManager.find(Category.class, categoryId);
	}

	@Override
	public void persist(Category category) {
		entityManager.persist(category);		
	}

	@Override
	public void update(Category category) {
		entityManager.merge(category);		
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Category> getAll() {
		return entityManager.createQuery("SELECT c FROM Category c").getResultList();
	}

}
